from paddle.base.libpaddle.pir.ops import accuracy

from model import create_model
from dataset import load_data
from train import test_model
import os
import paddle.io as io
import paddle
from paddle.optimizer import Adam
from paddle import nn


def invoke_model(MatFile):
    # 设置参数
    SNR_val = -4
    M_val = 25
    test_rule0 = 0
    test_rule = 1
    batch_size = 64

    lr = 4e-4
    gamma = 0.4
    seed = 10
    gpuserial = 0

    # 创建模型
    model = create_model()

    # 加载数据
    val_data = load_data(MatFile, test_rule0, test_rule)
    val_loader = io.DataLoader(dataset=val_data, batch_size=batch_size, shuffle=True)
    # 设置设备
    device = (
        paddle.CUDAPlace(gpuserial)
        if paddle.is_compiled_with_cuda()
        else paddle.CPUPlace()
    )
    model.to(device)

    # 检查模型权重文件是否存在
    model_weights_path = os.path.join(
        os.path.dirname(__file__), "model_weights.pdparams"
    )
    if not os.path.exists(model_weights_path):
        raise FileNotFoundError(f"模型权重文件 '{model_weights_path}' 不存在")

    # 加载模型权重
    model.set_state_dict(
        paddle.load(model_weights_path)
    )
    
    model.eval()
    # 创建优化器和损失函数
    criterion = nn.BCEWithLogitsLoss()
    optimizer = Adam(parameters=model.parameters(), learning_rate=lr)

    Accuracy, Test_Output = test_model(model, criterion, val_loader, device)

    return Accuracy, Test_Output
